package com.example.choupaiapp.main.activity.home;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.example.choupaiapp.R;
import com.example.choupaiapp.common.adapter.BaseAdapterHelper;
import com.example.choupaiapp.common.adapter.QuickAdapter;
import com.example.choupaiapp.common.ui.activity.CommonActivity;
import com.example.choupaiapp.common.util.Utils;
import com.example.choupaiapp.main.view.indexsidebar.City;
import com.example.choupaiapp.main.view.indexsidebar.LetterComparator;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.orhanobut.logger.Logger;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import org.greenrobot.eventbus.EventBus;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by ASUS on 2019/11/28.
 */

public class LocationCitySearchActivity extends CommonActivity {

    @BindView(R.id.search_et)
    EditText searchEt;
    @BindView(R.id.clear)
    ImageView clear;
    @BindView(R.id.listview)
    ListView listview;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    private List<String> stringList;
    private QuickAdapter<String> quickAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_location);
    }

    private void setSoftKeyboard(EditText editText) {
        editText.setFocusable(true);
        editText.setFocusableInTouchMode(true);
        editText.requestFocus();

        //为 commentEditText 设置监听器，在 DialogFragment 绘制完后立即呼出软键盘，呼出成功后即注销
        editText.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                if (inputMethodManager != null) {
                    if (inputMethodManager.showSoftInput(editText, 0)) {
                        editText.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                    }
                }
            }
        });
    }

    @Override
    protected void initView() {
        Type listType = new TypeToken<ArrayList<City>>() {
        }.getType();
        Gson gson = new Gson();
        final List<City> list = gson.fromJson(City.DATA, listType);
        Collections.sort(list, new LetterComparator());

        stringList = new ArrayList<>();

        quickAdapter = new QuickAdapter<String>(this, R.layout.item_city) {
            @Override
            protected void convert(BaseAdapterHelper helper, String item) {
                helper.setText(R.id.city_name, item);
            }
        };

        listview.setAdapter(quickAdapter);

        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Logger.e("city:" + quickAdapter.getItem(i));
                EventBus.getDefault().post("city:" + quickAdapter.getItem(i));
                finishActivity();
            }
        });

        searchEt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    if (!TextUtils.isEmpty(searchEt.getText().toString().trim())) {
                        //点击搜索的时候隐藏软键盘
                        InputMethodManager manager = (InputMethodManager) searchEt.getContext()
                                .getSystemService(Context.INPUT_METHOD_SERVICE);
                        manager.hideSoftInputFromWindow(searchEt.getWindowToken(), 0);
                        stringList.clear();
                        // 在这里写搜索的操作,一般都是网络请求数据
                        for (int i = 0; i < list.size(); i++) {
                            if(!TextUtils.isEmpty(list.get(i).name)){
                                if (list.get(i).name.contains(searchEt.getText().toString())) {
                                    stringList.add(list.get(i).name);
                                }
                            }

                        }
                        quickAdapter.clear();
                        quickAdapter.addAll(stringList);
                        quickAdapter.notifyDataSetChanged();

                    }
                    return true;
                }
                return false;
            }
        });

        setSoftKeyboard(searchEt);
    }

    @Override
    protected void initData() {

    }

    @OnClick({R.id.clear, R.id.cancel})
    public void onViewClicked(View view) {
        if (Utils.isDoubleClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.clear:
                searchEt.setText("");
                break;
            case R.id.cancel:
                finishActivity();
                break;
        }
    }
}
